<template>
    <div class="tableList">
        <el-dialog :visible.sync="visible" width="800px" @close='handleClose' :close-on-click-modal="false">
            <span class="title" slot="title">选择产品</span>
            <div class="dialogBody">
                <el-input placeholder="可搜索产品名称/编码/规格" v-model="form.searchName" size='mini' style="margin-bottom:10px">
                    <template slot="append">
                        <el-button type="primary" icon="el-icon-search" size="mini" plain @click="searchName">搜索
                        </el-button>
                    </template>
                </el-input>
                <el-table :data="tableData" border style="width: 100%;" max-height="500px"
                    :header-cell-style="{background:'#fafafa',color:'#000',fontWeight:400,fontSize:'12px'}"
                    :cell-style="{color:'#5a5a5a',fontSize:'12px',fontWeight:400}"
                    @selection-change="handleSelectionChange" :row-key="getRowKeys" ref="tableData">
                    <el-table-column type="selection" width="55" :reserve-selection='true' fixed>
                    </el-table-column>
                    <el-table-column label="序号" width="80">
                        <template slot-scope="scope">
                            <span>{{(form.page - 1) * (form.limit) + scope.$index + 1}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column v-for="(item,index) in tableGroup" :key="item.label" :label="item.name"
                        show-overflow-tooltip :min-width="item.width">
                        <template slot-scope="scope">
                            <code v-if='customImgSet(item.label, scope.row)'>
                                <p v-if='(JSON.parse(scope.row[item.label])).length <= 2'>
                                    <img :src="$global.uploadUrl + k.url" alt=""
                                        v-for="(k, i) in JSON.parse(scope.row[item.label])" :key="i" class="customImg"
                                        @click='costomImgPreview(i+1, (JSON.parse(scope.row[item.label])).length, JSON.parse(scope.row[item.label]))'>
                                </p>
                                <p v-else>
                                    <img :src="$global.uploadUrl + JSON.parse(scope.row[item.label])[0].url" alt=""
                                        class="customImg"
                                        @click='costomImgPreview(1, JSON.parse(scope.row[item.label]).length, JSON.parse(scope.row[item.label]))'>
                                    <span class='customImgMoreBox'>
                                        <div class='customImgMore'
                                            @click='costomImgPreview(2, JSON.parse(scope.row[item.label]).length, JSON.parse(scope.row[item.label]))'>
                                            <el-popover placement="top" max-width="400" trigger="hover">
                                                <div class='customImgMore' slot="reference">
                                                    +{{ JSON.parse(scope.row[item.label]).length - 2 }}</div>
                                                <img :src="$global.uploadUrl + k.url" alt=""
                                                    v-for="(k, i) in JSON.parse(scope.row[item.label])" :key="i"
                                                    style="margin-right:10px" width='60px' height='60px'
                                                    @click="costomImgPreview(i+1, JSON.parse(scope.row[item.label]).length, JSON.parse(scope.row[item.label]))">
                                            </el-popover>
                                        </div>
                                        <img :src="$global.uploadUrl + JSON.parse(scope.row[item.label])[1].url" alt=""
                                            class="customImg">
                                    </span>
                                </p>
                            </code>
                            <code v-else>
                                <code v-if="customSelectSet(item.label, scope.row)">
                                    <span v-for="(k, j) in customSelectList(item.label, scope.row)" :key="j"
                                        :style="customSelectStyle(item.label, scope.row, k)" class="customSelect">
                                        {{ k }}
                                    </span>
                                </code>
                                <code v-else>
                                    {{scope.row[item.label]}}
                                </code>
                            </code>
                        </template>
                    </el-table-column>
                    <div slot="empty">
                        <el-empty :image-size="100"></el-empty>
                    </div>
                </el-table>
                <div class="pagination">
                    <span>已选{{multipleSelection.length}}项</span>
                    <el-pagination v-if="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        :page-sizes="[10,20,50,100]" :page-size="form.limit" :current-page="currentPage"
                        layout="total,prev, pager, next,sizes" :total="total" background>
                    </el-pagination>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="mini" @click='visible = false'>取 消</el-button>
                <el-button type="primary" size="mini" @click="handleConfirm">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog :title="customImgData.title" :visible.sync="customImgData.visible" width='68%'>
            <el-carousel trigger="click" height="50vh" :autoplay='false' :initial-index='customImgData.initial'
                @change='handleCarousel' ref='carousel'>
                <el-carousel-item v-for="(item, i) in customImgData.list" :key="i">
                    <img :src="item.url" alt="" class='carouselImg'>
                </el-carousel-item>
            </el-carousel>
            <div class='imgDownLoad' @click='imgDownLoad'>
                <span class='el-icon-download'></span>
                下载
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {
        getListGroupByProduct,
        getListByProductId,
        productList        
    } from '@/api/baseController'
    import {
        customFieldOther
    } from '@/api/customFieldController'
    import group from './bom'
    export default {
        data() {
            return {
                tableData: [],
                tableGroup: [],
                form: {
                    searchName: '',
                    limit: 10,
                    page: 1
                },
                multipleSelection: [],
                total: 0,
                currentPage: 1,
                visible: false,
                customImgData: {
                    visible: false,
                    list: [],
                    title: '',
                    initial: 0,
                    num: 0
                },
                uniqueId: 1,
                info:{}
            }
        },
        mounted() {
            this.getCustomFieldOther({
                type: 'product'
            })
        },
        methods: {
            // 自定义字段
            getCustomFieldOther: async function (data) {
                const res = await customFieldOther(data)
                const filterData = res.data.filter(i => i.customFieldMess.fieldType != 'upload').map(i => {
                    return {
                        label: i.customFieldId,
                        name: i.name,
                        width: '180'
                    }
                })
                this.tableGroup = [...group, ...filterData]
            },
            getListByProductIdFn: async function (data) {
                const {way,row} = this.info
                console.log(this.info);
                let payload = {
                    productTable:[]
                }
                const res = await getListByProductId(data)
                let date = Date.now()
                payload.productTable = res.data.map((i, index) => {
                    return {
                        id: null,
                        uniqueId:  (this.uniqueId + index) + ':' + date,
                        parentId: way === 'addProduct' ? null : row.uniqueId,
                        productId: i.productId,
                        productCode:i.productCode,
                        productName:i.productName,
                        productSpecification:i.productSpecification,
                        productAttribute:i.productAttribute,
                        productUnit:i.productUnit,
                        unitUsage:1,
                        planedNumber:1,
                        workOrderCode:'待生成',
                        workOrderStartTimeAndEndTime:[
                            new Date().dateFormat('yyyy-MM-dd 00:00:00'),
                            new Date().dateFormat('yyyy-MM-dd 23:59:59')
                        ],
                        customFieldVos:[]
                    }
                })
                this.visible = false
                this.$emit('getProductTable',payload,this.info)
            },
            productListFn: async function (data) {
                const res = await productList(data)
                this.tableData = res.data.records
                this.tableData.forEach(item => {
                    if (item.customFieldVos !== null) {
                        item.customFieldVos.map(k => {
                            item[k.customFieldId] = k.value
                        })
                    }
                })
                this.total = res.data.total
            },
            searchName() {
                this.form.page = 1
                this.productListFn(this.form)
            },
            getRowKeys(row) {
                return row.id
            },
            add(info, uniqueId) {
                console.log(uniqueId);
                if (uniqueId) {
                    this.uniqueId = uniqueId
                }
                this.info = info
                this.productListFn(this.form)
                this.visible = true
            },
            //全选
            handleSelectionChange(val) {
                this.multipleSelection = val
            },
            //确认
            handleConfirm() {
                if(this.multipleSelection.length <= 0){
                    this.visible = false
                    return
                }
                let productIds = this.multipleSelection.map(i => i.id).toString()
                this.getListByProductIdFn({productIds,getChild:0})
            },
            handleClose() {
                this.currentPage = 1
                this.form = this.$options.data().form
                this.$refs.tableData.clearSelection()
            },
            // 自定义字段 复选框/单选框 列
            customSelectSet(t, d) {
                let state = false
                if (d.customFieldVos != null) {
                    d.customFieldVos.map(item => {
                        if (item.customFieldMess != null) {
                            if ((item.customFieldMess.fieldType == 'selectRadio' || item.customFieldMess
                                    .fieldType == 'selectChecked') && t == item.customFieldId) {
                                state = true
                            }
                        }
                    })
                    return state
                } else {
                    return false
                }
            },
            customSelectList(t, d) {
                if (d[t] == '' || d[t] == '[]') {
                    return []
                } else {
                    let data = []
                    try {
                        data = JSON.parse(d[t])
                    } catch {
                        data = d[t].split(',')
                        data[0] == '' ? data = [] : ''
                    }
                    data === Number(data) ? data = [data] : ''
                    return data
                }
            },
            customSelectStyle(t, d, v) {
                let style = {}
                if (d.customFieldVos != null) {
                    let obj = d.customFieldVos.find(res => {
                        return res.customFieldId == t
                    })
                    if (obj.value != '' && obj.value != '[]') {
                        if (obj.customFieldMess.fieldType == 'selectRadio') {
                            let color = JSON.parse(obj.customFieldMess.checkBox).find(res => {
                                return obj.value == res.value
                            })
                            if (color != undefined) {
                                return {
                                    color: color.color,
                                    background: (color.color).substr(0, 3) + 'a' + (color.color).substr(3, color.color
                                        .length - 4) + ', .1)'
                                }
                            } else {
                                return {
                                    color: '#333',
                                    background: '#f4f4f5'
                                }
                            }
                        }
                        if (obj.customFieldMess.fieldType == 'selectChecked') {
                            let color = JSON.parse(obj.customFieldMess.checkBox).find(res => {
                                return v == res.value
                            })
                            if (color != undefined) {
                                return {
                                    color: color.color,
                                    background: (color.color).substr(0, 3) + 'a' + (color.color).substr(3, color.color
                                        .length - 4) + ', .1)'
                                }
                            } else {
                                return {
                                    color: '#333',
                                    background: '#f4f4f5'
                                }
                            }
                        }
                    }
                }
            },
            // 自定义字段图片列
            customImgSet(t, d) {
                let state = false
                if (d.customFieldVos != null) {
                    d.customFieldVos.map(item => {
                        if (item.customFieldMess != null) {
                            if (item.customFieldMess.fieldType == 'picture' && t == item.customFieldId) {
                                state = true
                            }
                        }
                    })
                    return state
                } else {
                    return false
                }
            },
            // 自定义图片预览
            costomImgPreview(i, len, list) {
                this.customImgData.visible = true
                this.customImgData.title = '预览' + ' (' + i + '/' + len + ')'
                this.customImgData.initial = Number(i) - 1
                this.customImgData.list = list.map(item => {
                    return {
                        name: item.name,
                        url: this.$global.uploadUrl + item.url
                    }
                })
                this.customImgData.num = i - 1
                this.setActiveItem(i - 1)
            },
            setActiveItem(i) {
                if (this.$refs.carousel) {
                    this.$refs.carousel.setActiveItem(i)
                }
            },
            // 图片预览轮播切换
            handleCarousel(v) {
                this.customImgData.title = '预览' + ' (' + (Number(v) + 1) + '/' + this.customImgData.list.length + ')'
                this.customImgData.num = v
            },
            // 图片下载
            imgDownLoad() {
                window.open(this.customImgData.list[this.customImgData.num].url, "_blank");
            },
            //pageSize 改变时会触发
            handleSizeChange(val) {
                this.form.limit = val
                this.productListFn(this.form)
            },
            //currentPage 改变时会触发
            handleCurrentChange(val) {
                this.form.page = val
                this.currentPage = val
                this.productListFn(this.form)
                // this.getListGroupByProductFn(this.form)
            },
        }
    }
</script>

<style lang="less" scoped>
    .tableList {
        code{
            font-family: sans-serif;
        }
        .dialogBody {
            .pagination {
                span {
                    margin-top: 15px;
                    float: left;
                }

                border-top: 1px solid #EBEEF5;
            }
        }

        ::v-deep .el-dialog__body {
            padding: 30px 20px 0 20px;
        }

        ::v-deep .el-dialog__footer {
            text-align: center;

            .el-button {
                padding: 7px 35px;
            }
        }
    }
</style>